package com.utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.BarCodeEnum;
import com.zbkj.crmeb.enums.CategoryTypeEnum;
import com.zbkj.crmeb.enums.CrmebMerchantEnums;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.SuppliersIdEnum;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.Gallery;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.Product;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.ProductSku;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.StoreProductAttr;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.request.StoreProductAttrValueRequest;
import com.zbkj.crmeb.store.request.StoreProductCrmebRequest;
import com.zbkj.crmeb.store.response.PriceResult;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.system.service.SystemAttachmentService;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceProductUtil {
    @Autowired
    SystemAttachmentService systemAttachmentService;
    @Autowired
    StoreBrandService storeBrandService;
    @Autowired
    SupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    ICategoryMatchService categoryMatchService;
    
    /**
     * 价格调整
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @return
     * @return BuyerProductDO
     * @throws
     */
    public Product priceAdjustBuyer2Crmeb(Product product) {
        // 销售价
        BigDecimal salePrice = StringUtils.isNotEmpty(product.getErpPrice()) ? new BigDecimal(product.getErpPrice()) : BigDecimal.ZERO;

//        product.setSalePrice(PriceUtil.calePrice(new BigDecimal(Constants.RATE_BUYER_2_CRMEB_FLOAT).multiply(salePrice), Constants.RATE_BUYER_2_CRMEB).toString());
        product.setSalePrice(salePrice.toString());
        product.setPromoteFlag(false);

        String erpPromPriceStr = product.getErpPromPrice();
        BigDecimal erpPromPrice = StringUtils.isNotEmpty(erpPromPriceStr) ? new BigDecimal(erpPromPriceStr) : BigDecimal.ZERO;
        product.setErpPromPrice(erpPromPrice.toString());

        // 成本价换算
        String erpPriceStr = product.getErpPrice();
        product.setSourceCost(erpPriceStr);
        product.setErpPrice(erpPriceStr);
        product.setErpPromFlag(false);

        // 供应商名称处理
        String suppliersId = product.getSuppliersId();
        product.setSuppliersName(SuppliersIdEnum.getEnumValue(suppliersId));
//        product.setCost(PriceUtil.calePrice(new BigDecimal(product.getSourceCost()), Constants.RATE_BUYER_2_CRMEB_COST).toString());
        product.setCost(product.getSourceCost());
        // 品牌对应
        StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getOtherId, product.getBrandId())
                .eq(StoreBrand :: getType, 3)
                .eq(StoreBrand :: getStatus, true)
                .eq(StoreBrand :: getIsDeleted, false)
                .last("LIMIT 1")
                );
        StoreBrand storeBrand = null;
        if(null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
        }
        if(null != storeBrand) {
            product.setBrandId(storeBrand.getId().toString());
            product.setBrandName(storeBrand.getEnName());
        }
        // 处理单独品牌价格(无法做成配置的)
        if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
        	PriceResult priceResult = priceUtil.eur2Rmb(new BigDecimal(product.getOriginalPrice()));
            product.setSalePrice(PriceUtil.calePrice(priceResult.getPrice(), "0.65").toString());
            product.setExchangeRate(priceResult.getExchangeRate());
        }
        
        return product;
    }
    
    public StoreProductCrmebRequest priceAdjustEurope2Crmeb(StoreProductCrmebRequest product) {
    	PriceResult priceResult = priceUtil.eur2Rmb(null == product.getPrice() ? BigDecimal.ZERO : product.getPrice());
        BigDecimal price = priceResult.getPrice();
//        BigDecimal salePrice = PriceUtil.calePrice(new BigDecimal(Constants.RATE_EUROPE_2_CRMEB_FLOAT).multiply(price), Constants.RATE_EUROPE_2_CRMEB);
        BigDecimal salePrice = price;
//        BigDecimal cost = PriceUtil.calePrice(price, Constants.RATE_EUROPE_2_CRMEB_COST);
        BigDecimal cost = price;
        
        product.setPrice(salePrice);
        product.setErpPromFlag(false);
        product.setCost(cost);
        product.setSourceCost(price);
        product.getAttrValue().stream().forEach(obj -> {obj.setPrice(salePrice); obj.setCost(cost);});
        
        // 处理单独品牌价格(无法做成配置的)
        if("13De Marzo".equals(product.getBrandName())) {
            product.setPrice(PriceUtil.calePrice(priceUtil.eur2Rmb(product.getOtPrice()).getPrice(), "0.65"));
        }
        product.setExchangeRate(priceResult.getExchangeRate());
        
        return product;
    }
    
    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildCrmebProduct(Product product, List<ProductSku> productSkus) {
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();

        // 规格
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        // 颜色
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);
        // 金额处理
        BigDecimal price = null == product.getSalePrice() ? BigDecimal.ZERO : new BigDecimal(product.getSalePrice());
        BigDecimal promotePrice = null == product.getPromotePrice() ? BigDecimal.ZERO : new BigDecimal(product.getPromotePrice());
        BigDecimal originalPrice = null == product.getOriginalPrice() ? BigDecimal.ZERO : new BigDecimal(product.getOriginalPrice());
        BigDecimal cost = null == product.getCost() ? BigDecimal.ZERO : new BigDecimal(product.getCost());
        BigDecimal sourceCost = null == product.getSourceCost() ? BigDecimal.ZERO : new BigDecimal(product.getSourceCost());
        String goodsImg = product.getGoodsImg();
        // 合并成suk
        List<String> colorValueList = new ArrayList<String>();
        List<String> valueList = new ArrayList<String>();
        productSkus.forEach(buyerProductSku -> {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setSourceSkuId(buyerProductSku.getSkuId());
            storeProductAttrValueRequest.setPromotePrice(promotePrice);
            storeProductAttrValueRequest.setPrice(price);
            storeProductAttrValueRequest.setStock(buyerProductSku.getStock());
            storeProductAttrValueRequest.setOtPrice(originalPrice);
            storeProductAttrValueRequest.setCost(cost);
            storeProductAttrValueRequest.setSourceCost(sourceCost);
            storeProductAttrValueRequest.setImage(systemAttachmentService.clearPrefix(goodsImg));

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<String, String>();
            List<String> suk = new ArrayList<String>();
            String color = buyerProductSku.getColor();
            if (StringUtils.isNotBlank(color)) {
                linkedMap.put("颜色", color);
                if(!colorValueList.contains(color)){
                    colorValueList.add(color);
                }
                suk.add(color);
            }
            String size = buyerProductSku.getSize();
            if (StringUtils.isNotBlank(size)) {
                linkedMap.put("尺寸", size);
                if(!valueList.contains(size)){
                    valueList.add(size);
                }
                suk.add(size);
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            attrValueList.add(storeProductAttrValueRequest);
        });
        if (CollectionUtils.isNotEmpty(colorValueList)) {
            storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }
        
        // 抽取所有size属性去重
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        // 强制写一个 商户id 作为buyer商品标识标识
        productRequest.setMerId(CrmebMerchantEnums.BUYER.getMerchantId());
        productRequest.setContent(product.getGoodsCaizhi());
        productRequest.setKeyword(product.getGoodsCode());
        productRequest.setStoreInfo("");
        productRequest.setStoreName(product.getGoodsName());
        productRequest.setBrandId(Integer.valueOf(product.getBrandId()));
        productRequest.setBrandName(product.getBrandName());
        productRequest.setPostage(new BigDecimal(product.getShippingFee()));
        //售价
        productRequest.setPrice(price);
        //活动价
        productRequest.setPromotePrice(promotePrice);
        // 原价
        productRequest.setOtPrice(originalPrice);
        // 成本价
        productRequest.setCost(cost);
        //原成本价
        productRequest.setSourceCost(sourceCost);

        //活动价标记
        productRequest.setPromoteFlag(product.getPromoteFlag());
        productRequest.setErpPromFlag(product.getErpPromFlag());

        //供应商
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                .eq(Supplier :: getSuppliersName, product.getSuppliersId())
                .last("LIMIT 1")
                );
        if(null != supplier) {
            productRequest.setSuppliersId(supplier.getId());
            productRequest.setSuppliersName(supplier.getSuppliersName());
            productRequest.setBarCode(supplier.getBarcode() + product.getGoodsId());
        } else {
            productRequest.setSuppliersName(product.getSuppliersId());
            productRequest.setBarCode(BarCodeEnum.BUYER.getCode() + product.getGoodsId());
        }
        // 类目
        CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                .eq(CategoryMatch :: getType, CategoryTypeEnum.BUYER)
                .eq(CategoryMatch :: getOthCategoryId, product.getCatId())
                .last("LIMIT 1")
                );
        Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 0;
        productRequest.setCateId(categoryId);
        productRequest.setCateIds(Arrays.asList(categoryId));
        
        productRequest.setImage(goodsImg);
        productRequest.setBarCode(BarCodeEnum.BUYER.getCode() + product.getGoodsId());
        List<Gallery> gallerys = product.getGalleryDTO();
        if (CollectionUtils.isNotEmpty(product.getGalleryDTO())) {
            List<String> sliderImages = gallerys.stream().map(obj -> obj.getImgOriginal()).collect(Collectors.toList());
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSort(0);
        productRequest.setSpecType(true);
        productRequest.setIsEurope(ProductTypeEnum.BUYER.getCode());
        productRequest.setTempId(product.getStockArea());
        productRequest.setUnitName("件");
        productRequest.setLastPushTime(new Date());
        if (StringUtils.isNotBlank(product.getSuppliersId()) && StringUtils.equals(product.getSuppliersId(), String.valueOf(2))) {
            productRequest.setMerUse(true);
        }
        productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        productRequest.setImage(systemAttachmentService.clearPrefix(productRequest.getImage()));
        productRequest.setSliderImage(systemAttachmentService.clearPrefix(productRequest.getSliderImage()));
        
        return productRequest;
    }
    
}
